<template>
    <div class="bidding-container">
      <!-- 渐变背景层 -->
      <div class="background-layer"></div>
  
      <!-- 头部区域 -->
      <div class="header-section" style="margin-top: -100px;">
        <div class="header-content">
          <h1 class="animated-title">
            <span class="fire-icon">🔥</span> 限时竞拍 <span class="fire-icon">🔥</span>
          </h1>
          <div class="search-bar">
            <el-input 
              placeholder="搜索竞拍商品..." 
              v-model="searchKeyword"
              class="search-input"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </div>
  
      <!-- 商品展示区 -->
      <div class="main-content">
        <!-- 骨架屏加载 -->
        <div v-if="loading" class="skeleton-grid">
          <div 
            v-for="i in 6" 
            :key="i" 
            class="skeleton-card"
          >
            <el-skeleton :loading="true" animated>
              <template #template>
                <el-skeleton-item variant="image" class="skeleton-image" />
                <div class="skeleton-info">
                  <el-skeleton-item variant="h3" style="width: 80%" />
                  <el-skeleton-item variant="text" style="width: 60%" />
                  <div class="skeleton-footer">
                    <el-skeleton-item variant="text" style="width: 30%" />
                    <el-skeleton-item variant="text" style="width: 40%" />
                  </div>
                </div>
              </template>
            </el-skeleton>
          </div>
        </div>
  
        <!-- 空状态 -->
        <div v-else-if="products.length === 0" class="empty-state">
          <div class="empty-content">
            <!-- <img src="@/assets/empty-auction.png" class="empty-image" /> -->
            <h3>暂时没有竞拍商品哦</h3>
            <p>快去发布你的商品或稍后再来查看吧</p>
            <el-button 
              type="primary" 
              size="large" 
              @click="refresh"
              class="refresh-btn"
            >
              <el-icon><Refresh /></el-icon>
              <span>刷新页面</span>
            </el-button>
          </div>
        </div>
  
        <!-- 商品网格 -->
        <div v-else class="enhanced-product-grid">
          <div 
            v-for="product in filteredProducts" 
            :key="product.productId" 
            class="auction-card"
            @mouseenter="hoverCard = product.productId"
            @mouseleave="hoverCard = null"
          >
            <!-- 卡片标签 -->
            <div class="card-badges">
              <div class="badge hot" v-if="product.wants > 50">
                <el-icon><Fire /></el-icon>
                <span>热门竞拍</span>
              </div>
              <div class="badge ending" v-if="isEndingSoon(product.endTime)">
                <el-icon><Clock /></el-icon>
                <span>即将截标</span>
              </div>
              
            </div>
  
            <!-- 图片区域 -->
            <div class="card-media">
              <el-image 
                :src="getImageUrl(product.images)"
                :zoom-rate="1.2"
                :preview-src-list="getPreviewImages(product.images)"
                :initial-index="0"
                fit="cover"
                class="product-image"
                loading="lazy"
              >
                <template #error>
                  <div class="image-fallback">
                    <el-icon :size="50"><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              
              <!-- 悬浮遮罩 -->
              <transition name="fade">
                <div v-show="hoverCard === product.productId" class="hover-overlay">
                  <el-button 
                    type="primary" 
                    class="bid-button"
                    @click.stop="navigateToDetail(product.productId)"
                  >
                    <el-icon><Aim /></el-icon>
                    <span>立即出价</span>
                  </el-button>
                </div>
              </transition>
            </div>
  
            <!-- 商品信息 -->
            <div class="card-body">
              <h3 class="product-title">
                {{ product.productName }}
                <el-tooltip effect="dark" content="经过平台认证" placement="top">
                  <el-icon v-if="product.isCertified" class="certified-icon"><CircleCheckFilled /></el-icon>
                </el-tooltip>
              </h3>
              
              <div class="price-info">
                <div class="current-bid">
                  <span class="label">当前报价:</span>
                  <span class="value">¥{{ formatPrice(product.price) }}</span>
                </div>
              </div>
              <div class="time-remaining">
                 <template v-if="product.auction">
                  <div v-if="product.auction.status === 0" class="time-text">
                      <el-icon><Clock /></el-icon>
                      开始倒计时：{{ formatRemainTime(getStartRemain(product)) }}
                    </div>
                    <div v-else-if="product.auction.status === 1" class="time-text ending">
                      <el-icon><AlarmClock /></el-icon>
                      剩余时间：{{ formatRemainTime(getEndRemain(product)) }}
                    </div>
                   <div v-else class="time-text ended">
                     <el-icon><CircleCloseFilled /></el-icon>
                     竞拍已结束
                   </div>
                 </template>
                 <div v-else class="time-text no-auction">
                   <el-icon><Warning /></el-icon>
                   未设置竞拍
                 </div>
               </div>
              <div class="meta-info">
                <div class="statistics">
                  <div class="stat-item">
                    <el-icon><View /></el-icon>
                    <span>{{ product.click }}</span>
                  </div>
                  <div class="stat-item">
                    <el-icon><Star /></el-icon>
                    <span>{{ product.wants }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="my-wins-section">
    <el-badge :hidden="winProducts.length === 0" :value="winProducts.length">
      <el-button 
        type="success" 
        plain 
        @click="showWinProducts"
        class="my-wins-btn"
      >
        <el-icon><Trophy /></el-icon>
        我的竞得商品
      </el-button>
    </el-badge>

    <!-- 竞得商品弹窗 -->
    <el-dialog
      v-model="winDialogVisible"
      title="已竞得商品"
      width="70%"
      top="5vh"
    >
      <div v-loading="winLoading">
        <!-- 空状态 -->
        <div v-if="winProducts.length === 0" class="empty-wins">
          <el-empty description="暂无竞得商品">
            <el-button type="primary" @click="winDialogVisible = false">
              去参与竞拍
            </el-button>
          </el-empty>
        </div>

        <!-- 商品列表 -->
        <div v-else class="win-products-grid">
          <div 
            v-for="product in winProducts"
            :key="product.productId"
            class="win-product-card"
          >
            <el-image 
              :src="getImageUrl(product.images)"
              class="product-thumbnail"
              fit="cover"
            />
            
            <div class="product-info">
              <h4 class="product-name">{{ product.productName }}</h4>
              <div class="win-price">
                <span class="label">成交价：</span>
                <span class="value">¥{{ formatPrice(product.finalPrice) }}</span>
              </div>
              <div class="win-time">
                {{ formatTime(product.endTime) }} 截标
              </div>
            </div>

            <el-button 
              type="primary" 
              class="purchase-btn"
              @click="handlePurchase(product)"
            >
              立即购买
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
  import { useRouter , useRoute } from 'vue-router'
  import axios from 'axios'
  import { 
    Search, Refresh, Fire, Clock, Aim, CircleCheckFilled, View, Star, Picture, 
    WindPower,Trophy 
  } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  const router = useRouter()
  const route = useRoute()
  const products = ref([])
  const userBids = ref([])
  const loading = ref(true)
  const searchKeyword = ref('')
  const hoverCard = ref(null)
  const currentTime = ref(Date.now())
  const winDialogVisible = ref(false)
const winLoading = ref(false)
const winProducts = ref([])
  // 获取商品数据
const fetchProducts = async () => {
  try {
    // 获取商品数据
    const productsRes = await axios.get('http://localhost:8092/product/getProductBySaleType', {
      params: { saleType: 1 }
    })
    
    // 获取所有竞拍数据
    const auctionPromises = productsRes.data.data.map(p => 
  axios.get('http://localhost:8092/auction/getByProductId', {
    params: {  // 使用params配置项传递查询参数
      productId: p.productId 
    }
  })
)
    const auctionsRes = await Promise.all(auctionPromises)

    // 合并数据
    products.value = productsRes.data.data.map((p, index) => ({
      ...p,
      auction: auctionsRes[index].data.data || null,
      // 计算时间戳
      startTime: auctionsRes[index].data.data ? 
        new Date(auctionsRes[index].data.data.startTime).getTime() : 0,
      endTime: auctionsRes[index].data.data ? 
        new Date(auctionsRes[index].data.data.endTime).getTime() : 0
    }))
    console.log('12312312',products.value)
  } catch (error) {
    console.error('请求异常:', error)
  } finally {
    loading.value = false
  }
}
const formatRemainTime = (milliseconds) => {
  if(milliseconds <= 0) return '00:00:00'
  
  const hours = Math.floor(milliseconds / (1000 * 60 * 60))
  const minutes = Math.floor((milliseconds % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((milliseconds % (1000 * 60)) / 1000)
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
// 显示已竞得商品
const showWinProducts = async () => {
  try {
    winLoading.value = true
    winDialogVisible.value = true
    
    const bidsRes = await axios.get('http://localhost:8092/bid/geyBidByUserId', {
      params: { userId: route.query.userId }
    })
    
    const winningBids = bidsRes.data.data.filter(bid => bid.isWinning === 1)
    
    const productPromises = winningBids.map(bid => 
      axios.get('http://localhost:8092/product/getDetailBySingleId', {
        params: { productId: bid.productId }
      })
    )
    const productsRes = await Promise.all(productPromises)

    // 修改后的过滤逻辑
    winProducts.value = winningBids.reduce((acc, bid, index) => {
      const productData = productsRes[index].data.data[0] || {}
      // 添加状态过滤条件
      if (productData.productState !== 1) {
        acc.push({
          productId: bid.productId,
          productName: productData.productName,
          images: productData.images,
          finalPrice: bid.bidPrice,
          endTime: bid.bidTime
        })
      }
      return acc
    }, [])
    
  } catch (error) {
    console.error('获取失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    winLoading.value = false
  }
}

// 购买处理
const handlePurchase = (product) => {
  console.log('发起购买:', product)
  // ElMessage.info(`购买请求已发送：${product.productName}`)
  // 实际业务中这里调用购买接口
  if (product.productId) {
    router.push({
      path: '/buy',
      query: {
        productIds: product.productId,
        // 可以携带更多参数（可选）
        quantity: 1 ,// 默认购买数量，
        isSingle:1 ,// 是否单独购买
        price:product.finalPrice, // 单价,
        salesType:1
      }
    })
  } else {
    ElMessage.error('商品信息加载失败，请稍后重试')
  }
}

// 添加自动刷新逻辑
const timers = ref(new Map())

const setupTimers = () => {
  const timer = setInterval(() => {
    currentTime.value = Date.now()
  }, 1000)
  
  onBeforeUnmount(() => {
    clearInterval(timer)
  })
}
const getStartRemain = (product) => {
  return new Date(product.auction.startTime).getTime() - currentTime.value
}

const getEndRemain = (product) => {
  return new Date(product.auction.endTime).getTime() - currentTime.value
}
const calculateAuctionStatus = (start, end) => {
  const now = Date.now()
  if(now < start) return 0
  if(now > end) return 2
  return 1
}
  // 计算属性
  const filteredProducts = computed(() => {
    return products.value.filter(p => 
      p.productName.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  })
  
  // 图片处理
  const getImageUrl = (images) => {
    if (!images) return '/default-product.jpg'
    const firstImage = images.split(',')[0]
    return `http://localhost:8092${firstImage}`
  }
  
  const getPreviewImages = (images) => {
    return images.split(',').map(img => `http://localhost:8092${img}`)
  }
  
  // 价格格式化
  const formatPrice = (price) => {
    return Number(price).toFixed(2)
  }
  
  // 时间处理
  const isEndingSoon = (endTime) => {
    return endTime - Date.now() < 3600000 // 1小时内
  }
  

  const navigateToDetail = (productId) => {
   const routeData = router.resolve({
    path: '/auction/detail',
    query: { productId }
   })
   window.open(routeData.href, '_blank')  
  }
  
  const refresh = () => {
    loading.value = true
    products.value = []
    fetchProducts()
  }
  const formatTime = (datetime) => {
  if (!datetime) return '未知时间'
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }
  return new Date(datetime).toLocaleString('zh-CN', options)
}
  onMounted(() => {
  fetchProducts().then(() => {
    setupTimers()
    // 初始化状态
    products.value.forEach(p => {
      if(p.auction) {
        p.auction.realStatus = calculateAuctionStatus(
          new Date(p.auction.startTime).getTime(),
          new Date(p.auction.endTime).getTime()
        )
      }
    })
  })
})
  </script>

<style scoped>
.bidding-container {
  position: relative;
  min-height: 100vh;
  background: #f8fafc;
}

.background-layer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400px;
  background: linear-gradient(135deg, #6366f1 0%, #a855f7 50%, #ec4899 100%);
  clip-path: ellipse(100% 60% at 50% 0%);
  z-index: 0;
}

.header-section {
  position: relative;
  padding: 80px 20px 40px;
  text-align: center;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.animated-title {
  font-size: 3.5rem;
  color: white;
  margin-bottom: 30px;
  animation: float 3s ease-in-out infinite;
}

.fire-icon {
  display: inline-block;
  animation: flame 1.5s ease-in-out infinite;
}

.search-bar {
  max-width: 600px;
  margin: 0 auto;
}

.search-input {
  border-radius: 30px;
  overflow: hidden;
  
  :deep(.el-input__wrapper) {
    padding: 12px 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    
    &:hover {
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    }
  }
}

.main-content {
  position: relative;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px 80px;
  z-index: 1;
}

/* 骨架屏样式 */
.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
  padding: 20px;
}

.skeleton-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
}

.skeleton-image {
  height: 250px;
  width: 100%;
}

.skeleton-info {
  padding: 20px;
}

.skeleton-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

/* 空状态 */
.empty-state {
  background: white;
  border-radius: 20px;
  padding: 50px 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.empty-image {
  width: 300px;
  margin-bottom: 30px;
  opacity: 0.9;
}

.refresh-btn {
  padding: 12px 30px;
  border-radius: 12px;
  font-size: 16px;
  transition: transform 0.2s;
  
  &:hover {
    transform: translateY(-2px);
  }
}

/* 商品网格 */
.enhanced-product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
  padding: 20px;
}

.auction-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  position: relative;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12);
  }
}

.card-badges {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 2;
  display: flex;
  gap: 10px;
}

.badge {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: 500;
  
  &.hot {
    background: linear-gradient(45deg, #ff6b6b, #ff8787);
    color: white;
  }
  
  &.ending {
    background: linear-gradient(45deg, #f59e0b, #fbbf24);
    color: white;
  }
}

.card-media {
  position: relative;
  height: 250px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.hover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.bid-button {
  padding: 14px 30px;
  font-size: 16px;
  border-radius: 10px;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 15px rgba(99, 102, 241, 0.3);
  }
}

.card-body {
  padding: 20px;
}

.product-title {
  font-size: 18px;
  color: #1e293b;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.certified-icon {
  color: #3b82f6;
  font-size: 18px;
}

.price-info {
  margin: 15px 0;
}

.current-bid {
  font-size: 20px;
  color: #ef4444;
  font-weight: 700;
  
  .label {
    font-size: 14px;
    color: #64748b;
    margin-right: 8px;
  }
}

.start-price {
  font-size: 14px;
  color: #94a3b8;
}

.time-remaining {
  margin: 20px 0;
}

.time-text {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #ef4444;
  font-weight: 500;
  margin-top: 8px;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.seller-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.seller-name {
  color: #475569;
  font-weight: 500;
}

.statistics {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #64748b;
  font-size: 14px;
}

/* 动画 */
@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

@keyframes flame {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.8; transform: scale(1.05); }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.time-remaining {
  margin: 12px 0;
  padding: 8px;
  background: #f8fafc;
  border-radius: 8px;
  font-size: 14px;
}

.time-text {
  display: flex;
  align-items: center;
  gap: 8px;
  
  &.ending {
    color: #e53e3e;
    font-weight: 600;
  }
  
  &.ended, &.no-auction {
    color: #718096;
  }
  
  .el-icon {
    font-size: 16px;
  }
}
.my-wins-section {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 2000;
}

.my-wins-btn {
  padding: 15px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.win-products-grid {
  display: grid;
  gap: 20px;
  padding: 10px;
}

.win-product-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  margin-right: 20px;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  margin: 0 0 8px;
  font-size: 16px;
  color: #1a1a1a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.win-price {
  font-size: 14px;
  color: #e53e3e;
}

.win-price .label {
  color: #666;
}

.win-time {
  font-size: 12px;
  color: #909399;
}

.purchase-btn {
  margin-left: 20px;
  padding: 10px 20px;
  border-radius: 8px;
}

.empty-wins {
  padding: 40px 0;
}
</style>